﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Frm.Base;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Frm;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using System.Text.RegularExpressions;

namespace Ledict.ConditionExtract.Frm.DataProcess
{
    /// <summary>
    /// 民事数据处理窗体（各业务考虑后期各自的特殊性，独立开） todo by zhangpeng 2016-12-14
    /// </summary>
    public partial class CivilDataProcessNew1 : BaseForm
    {
        #region 界面初始化

        //静态锁
        private static readonly object Lock = new object();

        static CivilDataProcessNew1 _default;
        public static CivilDataProcessNew1 Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (Lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new CivilDataProcessNew1();
                        }
                    }

                }
                return _default;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CivilDataProcessNew1()
        {
            InitializeComponent();
            //NowProcessNode.TreeView.AfterExpand += new TreeViewEventHandler(NowProcessNode_AfterExpand);
            cbTreeViewSysCourt.TreeView.CheckBoxes= t_Case_HeadWords.TreeView.CheckBoxes = false;
        }

        #endregion

        readonly Express_SourceBLL sourceBll = new Express_SourceBLL();
        readonly TreeDataBLL trbll = new TreeDataBLL();
        readonly CaseCauseBLL casecausebLL = new CaseCauseBLL();
        readonly Express_WordBLL wordbll = new Express_WordBLL();
        readonly Express_AddElement addelementbll = new Express_AddElement();
        readonly NewIDBLL newid = new NewIDBLL();

        readonly ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        readonly RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        readonly WorkThread_Public work = new WorkThread_Public();
        readonly WordBankKeyWordsBLL wordbankkeywordsbll = new WordBankKeyWordsBLL();
        readonly Express_WordBankRelBLL express_wordbankrelbll = new Express_WordBankRelBLL();
        readonly WordBankBLL wordbankbll = new WordBankBLL();
        readonly DataProcess_EditNode dataprocess_editnode = new DataProcess_EditNode();
        readonly Express_MatchSituationBLL express_matchsituationbll = new Express_MatchSituationBLL();
        private string ccName = string.Empty;


        #region 共有变量
        private string sort = "";
        private string IsASC = "";
        private string SelectText = "";
        private string SelectWBK_ID = "";
        private TreeNode clicknode;
        //private string IsAddData = "";

        private string TypeName = "刑事罪名";
        string EW_IDText = "";
        int GridViewRowNumber;

        int IsContentOrAddElement = 1;//1为编辑文本0 为编辑要素
        private string FirId = "1000";
        private List<TreeNode> NodeList = new List<TreeNode>();
        //案由数据表
        private static DataTable sysCaseCauseTable = new DataTable();
        Sys_CourtBLL sysCourtBll = new Sys_CourtBLL();
        //法院数据表
        private static DataTable sysCourtTable = new DataTable();

        #endregion

        #region 初始化树
        /// <summary>
        /// 初始化树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataProcess_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            DV_AddElement.AutoGenerateColumns = false;
            DV_AddElement.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            //加载案由数据
            LoadSysCaseCauseData();
            //GetData("t_Case_HeadWords");
            GetData("t_Case_JudicialProcedure");
            GetData("t_Case_Property");
            GetData("t_Case_ParagraphType");

            //加载法院数据
            LoadSysCourtData();
            TypeName = "民事案由";
            CaseCauseTree();

        }
        #endregion

        #region 左侧树

        public void CaseCauseTree()
        {
            #region 初始化
            tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            StacticQuery.Text = "";
            CurrNodeNum.Text = "";
            SumQuery.Text = "";
            #endregion

            var dt = trbll.GetCauseTree_Two("", 0);// 第一层

            if (dt.Rows.Count > 0)
            {
                var arrayDR = dt.Select("name='" + TypeName + "'");

                foreach (var caseTreeNodeRode in arrayDR)
                {
                    var node = new TreeNode();

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
                    node.Tag = caseTreeNodeRode["id"];
                    node.Name = LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"] + "," + caseTreeNodeRode["TableName"]);
                    FirId = caseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 0).Rows.Count > 0)//第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }
            col.AddRange(new List<Color> { Color.FromArgb(192, 192, 192), Color.FromArgb(250, 235, 215), Color.FromArgb(240, 255, 255), Color.FromArgb(112, 128, 105), Color.FromArgb(227, 168, 105), Color.FromArgb(176, 224, 230), Color.FromArgb(64, 224, 208), Color.FromArgb(240, 230, 140), Color.FromArgb(0, 255, 127), Color.FromArgb(244, 164, 96), Color.FromArgb(218, 112, 214), Color.FromArgb(221, 160, 221), Color.FromArgb(255, 127, 80), Color.FromArgb(188, 143, 143), Color.FromArgb(61, 145, 64) });

        }

        /// <summary>
        /// 加载案由数据
        /// </summary>
        private void LoadSysCaseCauseData()
        {
            sysCaseCauseTable = casecausebLL.GetSysCaseCauseData();
            if (sysCaseCauseTable.Rows.Count > 0)
            {
                if (sysCaseCauseTable.Select("ID in('1000','1477','2329','2415','2449') ").Length > 0)
                {
                    DataTable sysCaseCausedt = sysCaseCauseTable.Select(" ID in('1000','1477','2329','2415','2449') ").CopyToDataTable<DataRow>();
                    foreach (DataRow dr in sysCaseCausedt.Rows)
                    {
                        TreeNode node = new TreeNode() { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        node.Nodes.Add(new TreeNode());
                        t_Case_HeadWords.TreeView.Nodes.Add(node);
                    }
                    t_Case_HeadWords.DropDownStyle = ComboBoxStyle.DropDown;
                    t_Case_HeadWords.TreeView.AfterExpand += TreeView_AfterExpandCaseCause;
                }
            }
        }

        /// <summary>
        /// 案由数据展开节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterExpandCaseCause(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            DataTable dt = new DataTable();
            if (sysCaseCauseTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").Length > 0)
            {
                dt = sysCaseCauseTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        if (sysCaseCauseTable.Select(" ParentID='" + node.Tag.ToString() + "' ").Length > 0)
                        {
                            DataTable dtt = sysCaseCauseTable.Select(" ParentID='" + node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                            if (dtt != null && dtt.Rows.Count > 0)
                            {
                                node.Nodes.Add(new TreeNode());
                            }
                        }
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 加载法院数据
        /// </summary>
        private void LoadSysCourtData()
        {
            sysCourtTable = sysCourtBll.GetSysCourtData();
            if (sysCourtTable.Rows.Count > 0)
            {
                if (sysCourtTable.Select(" ParentID is null  or ParentID=''  ").Length > 0)
                {
                    DataTable sysCourtdt = sysCourtTable.Select(" ParentID is null  or ParentID='' ").CopyToDataTable<DataRow>();
                    foreach (DataRow dr in sysCourtdt.Rows)
                    {
                        TreeNode node = new TreeNode() { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        node.Nodes.Add(new TreeNode());
                        cbTreeViewSysCourt.TreeView.Nodes.Add(node);
                    }
                    cbTreeViewSysCourt.DropDownStyle = ComboBoxStyle.DropDown;
                    cbTreeViewSysCourt.TreeView.AfterExpand += TreeView_AfterExpand; ;
                }
            }
        }

        /// <summary>
        /// 法院节点树展开事件 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            DataTable dt = new DataTable();
            if (sysCourtTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").Length > 0)
            {
                dt = sysCourtTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        if (sysCourtTable.Select(" ParentID='" + node.Tag.ToString() + "' ").Length > 0)
                        {
                            DataTable dtt = sysCourtTable.Select(" ParentID='" + node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                            if (dtt != null && dtt.Rows.Count > 0)
                            {
                                node.Nodes.Add(new TreeNode());
                            }
                        }
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 显示下一级树节点
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            try
            {
                var caseTreeNodeRode = GetChild(parentNode);
                if (caseTreeNodeRode.Rows.Count == 0)
                    return;
                for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)//下级
                {

                    var node = new TreeNode();

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                    node.Tag = caseTreeNodeRode.Rows[i]["id"];
                    node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"] + "," + caseTreeNodeRode.Rows[i]["TableName"]);

                    if (node.Text == "组合" || GetChild(node).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }

                    parentNode.Nodes.Add(node);
                    NodeList.Add(node);
                }
            } 
            catch (Exception ex)
            {
                Log.WriteLog("CaseCauseTreeChild 方法报错：" + ex.Message);
            }
        }
        /// <summary>
        /// 获取下一级树节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <returns></returns>
        private DataTable GetChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();
            DataTable caseTreeNodeRode;
            //var name = parentNode.Name.Split(',');
            //var ptype = Convert.ToInt32(name[0]);
            //parentNode.Text == "单一" ||
            if ( parentNode.Text == "组合" || pid.StartsWith("EMS"))
            {
                DataTable dt = express_matchsituationbll.GetExpressNodeData(pid);
                if (dt != null && dt.Rows.Count > 0)
                {
                    return dt;
                }
                else
                {
                    return new DataTable();
                }
            }
            if (parentNode.Text == "单一")
            {
                //单一的话节点取单一节点的父节点
                SYS_Express_MatchSituation sem = express_matchsituationbll.GetMatchSituation(pid);
                pid = sem.ParentID.ToString();
            }
            SYS_CaseCause scc = casecausebLL.GetCaseCauseByCCID(pid);
            //if (scc.AllParentName.Contains("民间借贷纠纷") && scc.AllParentName.Contains("争议焦点要素"))
            if (scc.AllParentName.Contains("争议焦点要素"))
            {
                var name = parentNode.Name.Split(',');
                var ptype = Convert.ToInt32(name[0]);
                //16争议焦点 17裁判理由
                //节点是争议焦点类型的去组合表里面找，如果找到则子节点为组合和单一，否则直接为该节点的子节点
                if (ptype == 16)
                {
                    DataTable dt = express_matchsituationbll.GetExpressNodeData(pid);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        return dt;
                    }
                    else
                    {
                        caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0);
                        return caseTreeNodeRode;
                    }
                }
                else if (ptype == 17 && scc.AllParentName.Contains("组合"))
                {
                    return new DataTable();
                }
                else
                {
                    caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0);
                    return caseTreeNodeRode;
                }
            }//scc.AllParentName.Contains("民间借贷纠纷") &&
            else if ( scc.AllParentName.Contains("理由要素"))
            {
                var name = parentNode.Name.Split(',');
                var ptype = Convert.ToInt32(name[0]);
                //22裁判结果
                if (ptype == 22)
                {
                    DataTable dt = express_matchsituationbll.GetExpressNodeData(pid);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        return dt;
                    }
                    else
                    {
                        caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0);
                        return caseTreeNodeRode;
                    }
                }
                else if (ptype == 17)
                {
                    return new DataTable();
                }
                else
                {
                    caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0);
                    return caseTreeNodeRode;
                }
            }
            else
            {
                caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0);
                return caseTreeNodeRode;
            }
        }

        /// <summary>
        /// 展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (e.Node.FirstNode.Tag == null)
                {
                    e.Node.Nodes.Clear();

                    CaseCauseTreeChild(e.Node);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("展开列表发生错误：" + ex.Message);
                MessageBox.Show("展开列表发生错误："+ex.Message);
            }
        }

        /// <summary>
        /// 选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (clicknode != null)
                    clicknode.ForeColor = Color.Black;
                clicknode = e.Node;//保存节点

                clicknode.ForeColor = Color.Red;
                //IsAddData = "";
                SelectText = "";
                SelectWBK_ID = "";
                if (clicknode.Text.Contains("（"))
                {
                    panel_Attribute.Enabled = false;
                }
                else
                {
                    panel_Attribute.Enabled = true;
                }

                ShowRegText();

                //清空逻辑段文本
                textBox1.Text = string.Empty;


                //判断当前节点的上级节点文本是否包含“+”，包含则当前节点显示表述数据（民事的特殊需求,只适用于民事下的组合节点） todo by zhangpeng 2017-02-06
                //if ((clicknode.FullPath.IndexOf("\\组合\\", StringComparison.Ordinal) != -1 && clicknode.Parent.Text.Contains("+")) || clicknode.FullPath.IndexOf("\\单一\\", StringComparison.Ordinal) != -1)
                {
                    dataPagerMain.ChangePageNumber(1);

                    GetConditionPurposeList(clicknode.Tag.ToString());
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("tVCaseCause_AfterSelect发生错误：" + ex.Message + " clicknode:" + clicknode);
                MessageBox.Show("tVCaseCause_AfterSelect发生错误:"+ex.Message);
            }
            //UpdateCC_IsShowExpress1(clicknode);
            //else
            //{
            //    dataGridView1.DataSource = new DataTable();
            //}
        }


        /// <summary>
        /// 根据所选节点，获取该节点对应的表述用途列表
        /// </summary>
        /// <param name="ccId">节点ID</param>
        private void GetConditionPurposeList(string ccId)
        {
            try
            {
                cbtConditionPurpose.TreeView.Nodes.Clear();
                cbtConditionPurpose.Text = null;
                //根据CCID，获取对应节点的用途列表（去重）
                var dt = sourceBll.GetPurposeDtByCcid(ccId);
                if (dt != null && dt.Rows.Count > 0)
                {
                    var rows = dt.Select(" AM_Name like '%表述%' ");
                    foreach (var dataRow in rows)
                    {
                        var node = new TreeNode
                        {
                            Text = dataRow["AM_Name"].ToString(),
                            Name = dataRow["AM_Name"].ToString(),
                            Tag = dataRow["AM_ID"]
                        };
                        cbtConditionPurpose.TreeView.Nodes.Add(node);
                    }

                    //cbtConditionPurpose.Select(0, 1);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("GetConditionPurposeList发生错误：" + ex.Message + " ccid:" + ccId);
                MessageBox.Show("GetConditionPurposeList发生错误:" + ex.Message);
            }

        }

        /// <summary>
        /// 表述用途选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbtConditionPurpose_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbtConditionPurpose.Text))
                return;
            //根据CCID和用途ID，查询对应的表述正则
            ShowRegText(cbtConditionPurpose.TreeView.SelectedNode.Tag.ToString());
        }



        /// <summary>
        /// 是否有用情形
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool IsUseFul(TreeViewEventArgs e)
        {
            //int type = Convert.ToInt32(e.Node.Name.ToString().Split (',')[0]);
            //if (type == 4 || type == 5 || type == 6 || type == 7 || type == 8)
            //{
            return true;
            //}
            //return false;
        }
        #endregion

        #region 右侧信息列表
        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            if (clicknode != null)
            {
                var startRowIndex = e.StartRowIndex;
                //var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                DataTable dtt = new DataTable();
                var id = clicknode.Tag.ToString();
                //第一种表述节点
                //第二种原SYS_CaseCause节点
                //int ismatch = IsMatch.Checked ? 1 : 0; //todo by zhangpeng:

                //int ismatch = 0; //默认0
                //  var affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                //2017-5-27 ljj 修改

                var affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                //2017-5-27 ljj 修改
                //根据ccid去SYS_Express_MatchSituation表中取msid，如果有则根据msid取数据，否则直接从SYS_Express_Word_Process 表中取
                DataTable msIdtb = expresitu.getES_IDsByCCId2(id, affirmIdeaResult);
                StringBuilder msid = new StringBuilder();
                if (msIdtb != null && msIdtb.Rows.Count > 0)
                {
                    dtt = wordbll.GetExtractContentByMsID(id, affirmIdeaResult);
                    //if (msIdtb.Rows.Count > 0)
                    //{
                    //    foreach (DataRow item in msIdtb.Rows)
                    //    {
                    //        msid.Append("'" + item["MS_ID"].ToString() + "',");
                    //    }


                        
                    //}
                }
                else
                {
                    dtt = wordbll.GetExractContent(id, sort, IsASC, SelectText, SelectWBK_ID, 0);
                }
                //DataTable dt1 = wordbll.GetExtractContentByMsID(id);
                //if (dt1 != null && dt1.Rows.Count > 0)
                //{
                //    dt.Merge(dt1);
                //}
                //DataView dv = dt.DefaultView;
                //DataTable dtt = dv.ToTable(true);


                //    }
                //}
                //var msId = expresitu.getES_IDsByCCId1(id); //expresitu.GetES_IDsByCCId(id, null, affirmIdeaResult);
                //if (string.IsNullOrEmpty(msId))
                //{
                //    msId = id;
                //}
                //dt = wordbll.GetExractContent(msId, sort, IsASC, SelectText, SelectWBK_ID, 0);


                if (dtt.Rows.Count > 0)
                    {
                        e.TotalCount = dtt.Rows.Count;
                        var newdt = new DataTable();
                        newdt = dtt.Clone();
                        var dr = dtt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                        for (var i = 0; i < dr.Length; i++)
                        {
                            newdt.ImportRow(dr[i]);
                        }
                        dataGridView1.DataSource = newdt;
                    }
                    else
                    {
                        dataGridView1.DataSource = new DataTable();
                    }
                }

            }
        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ToAddWordBanks()
        {
            tabControl1.SelectTab("tabPage2");
            if (null != clicknode)
            {
                linkAddWB.Text = string.Format("<<{0}", clicknode.Text);
            }
            GetWordkeyByCCId();
        }

        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ShowRegText(string purposeId = null)
        {
            var dt = new DataTable();
            dt.Columns.Add("ER_Name");
            dt.Columns.Add("ER_OperateType");
            dt.Columns.Add("ER_RegexText");
            dt.Columns.Add("EI_ID");
            var id = clicknode.Tag.ToString();
            //获取ccId
            id = expresitu.GetES_SituationIdsById(id);

            //获取指定表述ID和选择用途下的正则
            DataTable dt1 = casecausebLL.GetRegCodeByJudgeBook1(id);
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                string regCode = dt1.Rows[0]["CC_RegexInfoCode"].ToString();
                string eiID = dt1.Rows[0]["EI_ID"].ToString();
                var reglist = getregex.GetRegexs(regCode);
                foreach (var item in reglist)
                {
                    var dr = dt.NewRow();
                    dr[0] = item.ER_Name;
                    switch (item.ER_OperateType)
                    {
                        case 1:
                            dr[1] = "提取";
                            break;
                        case 2:
                            dr[1] = "替换";
                            break;
                        case 3:
                            dr[1] = "匹配";
                            break;

                    }
                    dr[2] = item.ER_RegexText;
                    dr[3] = eiID;
                    dt.Rows.Add(dr);
                }
            }
            GV_Reg.DataSource = dt;
        }


        /// <summary>
        /// 转到节点树界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl1.SelectTab("tabPage1");

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DV_AddElement_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2)  //添加节点重跑数据
            {
                try
                {
                    OpenNodeTree();
                }
                catch (Exception error)
                {

                    MsgBox.Err("添加要素失败!");
                    Log.ErrorLog(error.Message);

                }
            }
            else if (e.ColumnIndex == 0)
            {
                // SelectText  = WhereLike.ToWherelike(DV_AddElement.Rows[e.RowIndex].Cells["Element"].Value.ToString().Replace("\r\n", ""), "EW_Content", 1);  
                SelectWBK_ID = DV_AddElement.Rows[e.RowIndex].Cells["WBK_ID"].Value.ToString();
                SelectText = "";

                dataPagerMain.ChangePageNumber(1);

            }

        }
        private void GetWordkeyByCCId()
        {
            if (clicknode != null)
            {
                var id = clicknode.Tag.ToString();

                //第一种表述节点
                //第二种原SYS_CaseCause节点
                //int ismatch = IsMatch.Checked ? 1 : 0; //构成不构成，刑事的特殊性，民事不需要 todo by zhangpeng


                var affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                id = expresitu.GetES_IDsByCCId(id, null, affirmIdeaResult);
                var wordBankKeysdt = wordbll.GetAllwordBankKeys(id);
                DV_AddElement.DataSource = wordBankKeysdt;

            }
        }

        List<Color> col = new List<Color>();

        /// <summary>
        /// 编辑列表（单击）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
              int i=  dataGridView1.Rows[e.RowIndex].Cells["wordPurpose"].FormattedValue.ToString() == "争议焦点" ? 1 : 2;
                #region 对勾和差
                if (e.ColumnIndex == 8 || e.ColumnIndex == 9)
                {
                    var checkCellRight = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["Right"];
                    var checkCellwrong = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["wrong"];
                    if (e.ColumnIndex == 8)
                    {
                        if (Convert.ToBoolean(checkCellRight.Value))
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                        else
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }

                    }
                    if (e.ColumnIndex == 9)
                    {
                        if (Convert.ToBoolean(checkCellwrong.Value))
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }
                        else
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                    }

                    var model = new SYS_Express_Word();
                    model.EW_Right = Convert.ToInt32(checkCellRight.Value);
                    model.EW_Wrong = Convert.ToInt32(checkCellwrong.Value);
                    model.EW_ID = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                    model.EW_WordPurpose = dataGridView1.Rows[e.RowIndex].Cells["wordPurpose"].FormattedValue.ToString() == "争议焦点" ? 1 : 2;
                    if (model.EW_Right == 1)//添加到表述库加工
                    {
                        wordbll.UpdateChooseState_Process(model);

                        model = wordbll.GetModel_Process(dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString());

                        UpdateCC_IsShowExpress(clicknode);

                        if (!wordbll.Exists_Word(model))
                        {
                            model.EW_WordPurpose = dataGridView1.Rows[e.RowIndex].Cells["wordPurpose"].Value.ToString() == "争议焦点" ? 1 : 2;
                            wordbll.Add_Word(model);//添加word 表
                        }
                    }
                    else if (model.EW_Wrong == 1)
                    {
                        wordbll.Delete_Word(model.EW_ID);
                        UpdateCC_IsShowExpress1(clicknode);
                    }
                }

                #endregion
                //if (e.ColumnIndex == 2)  //编辑文本
                //{
                EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();

                textBox1.Text = "";
                textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();

                NewMethod();

                //byte[] buffer = Encoding.UTF8.GetBytes(dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString());
                //textBox1.Text = Encoding.GetEncoding("UTF-8").GetString(buffer);
                GridViewRowNumber = e.RowIndex;
                ColorWord();

                // }

            }

        }


        private void UpdateCC_IsShowExpress1(TreeNode nowNode)
        {
            //查看节点关联的数据
            var oldid = nowNode.Tag.ToString();
            var id = "";
            var count = 0;
            if (!oldid.Contains("EMS"))
            {
                id = expresitu.GetES_IDsByCCId(oldid, 1, "1");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(oldid, 1, "0");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(oldid, 0, "1");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(oldid, 0, "2");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
            }
            else
            {
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
            }
            //没数据且没下级
            if (nowNode.Nodes.Count == 0 && count == 0)
            {
                wordbll.UpdateCC_IsShowExpress(nowNode.Tag.ToString(), 0);
                var nowNodePid = nowNode.Parent;
                //去掉当前节点
               // tVCaseCause.Nodes.Remove(nowNode);

                //递归处理父级 
                if (nowNodePid != null)
                    UpdateCC_IsShowExpress1(nowNodePid);
            }
        }


        private void NewMethod()
        {
            int i = 1;
            StringBuilder sb = new StringBuilder();
            DataTable dt = (DataTable)GV_Reg.DataSource;
            if (dt != null && dt.Rows.Count > 0)
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[\u4e00-\u9fa5]+");//正则表达式
                foreach (DataRow item in dt.Rows)
                {
                    foreach (Match v in reg.Matches(item["ER_RegexText"].ToString()))
                    {
                        sb.Append(v.ToString() + ",");
                    }
                }
            }
            string item1 = sb.ToString();
            if (!string.IsNullOrEmpty(item1))
            {
                string[] items = item1.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string item2 in items)
                {

                    int index = textBox1.Find(item2, 0, textBox1.Text.Length, RichTextBoxFinds.None);
                    //名称
                    while (index != -1)
                    {
                        i++;
                        if (i >= col.Count)
                        {
                            i = 0;
                        }
                        string strr = textBox1.SelectedText;
                        textBox1.SelectionBackColor = col[i];
                        if (index + item1.Length >= textBox1.Text.Length)
                        {
                            index = -1;
                        }
                        else
                        {
                            index = textBox1.Find(item1, index + item2.Length, textBox1.Text.Length, RichTextBoxFinds.None);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 自己和所有父级节点记状态
        /// </summary>
        /// <param name="nowNode"></param>
        private void UpdateCC_IsShowExpress(TreeNode nowNode)
        {

            wordbll.UpdateCC_IsShowExpress(nowNode.Tag.ToString(), 1);
            if (nowNode.Parent != null)
                UpdateCC_IsShowExpress(nowNode.Parent);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Click(object sender, EventArgs e)
        {
            var DeleteID = "";
            int num = 0;
            for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                if (Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要删除的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    bool res = false;
                    for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                        if (Convert.ToBoolean(check.Value))
                        {
                            DeleteID = dataGridView1.Rows[i].Cells["EW_ID"].Value.ToString();
                            if (DeleteID != "")
                            {

                                wordbll.Delete_WordProcess(DeleteID);
                                res = true;
                            }

                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("删除成功!");
                    }
                    else
                    {
                        MsgBox.Warn("删除失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Err("删除失败!");
                    Log.ErrorLog(error.Message);

                }
                dataPagerMain.ChangePageNumber(1);
            }
        }



        /// <summary>
        /// 2017年5月15日 ljj-update 该方法从未被使用
        /// 显示窗体，自动将窗体填满父窗体的工作区
        /// </summary>
        /// <param name="childForm"></param>
        //private void ShowForm(Form childForm)
        //{
        //    childForm.MdiParent = MdiParent;
        //    childForm.StartPosition = FormStartPosition.CenterParent;
        //    childForm.Show();
        //    childForm.Activate();
        //    childForm.Dock = DockStyle.Fill;
        //    var size = childForm.Size;
        //    var location = childForm.Location;
        //    childForm.Dock = DockStyle.None;
        //    childForm.Size = size;
        //    childForm.Location = location;
        //}
        /// <summary>
        /// 修改文本 
        /// </summary>=""
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWord_Click(object sender, EventArgs e)
        {
            if (IsContentOrAddElement == 1)
            {
                if (dataGridView1.SelectedRows.Count > 0 && !string.IsNullOrEmpty(textBox1.Text))
                {
                    EW_IDText = dataGridView1.SelectedRows[0].Cells["EW_ID"].Value.ToString();

                    if (wordbll.UpdateContent(EW_IDText, textBox1.Text))
                    {
                        MessageBox.Show("修改成功!");
                    }
                    else
                    {
                        MessageBox.Show("修改失败!");
                    }
                    var checkCellwrong = dataGridView1.SelectedRows[0].Cells["EW_Content"];
                    checkCellwrong.Value = textBox1.Text;
                }
            }

        }
        #endregion

        #region 多线程

        WorkThread workObj = new WorkThread();
        //工作对象
        private Thread workThread;





        //暂停(只针对第一次加工数据)
        private void Endbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (workThread != null)
                {
                    workThread.Abort();
                    workThread = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        // 显示进度条
        public void ShowProgress(int maxCount, int currentCount)
        {
            if (progressBar1.InvokeRequired == false)
            {
                if (currentCount < maxCount)
                {
                    progressBar1.Maximum = maxCount;

                    progressBar1.Value = currentCount;
                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("当前{0}条|总共{1}条", currentCount, maxCount);
                }
                else if (currentCount == maxCount)
                {
                    progressBar1.Maximum = maxCount;
                    progressBar1.Value = currentCount;

                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("已完成，共{0}条", maxCount);
                    workThread = null;
                    StaticCacheBLL.plotchildDict = new Dictionary<string, DataTable>();//清除规则缓存
                }
            }
            else
            {
                ProcessShow processshow = ShowProgress;
                Invoke(processshow, maxCount, currentCount);
            }

        }


        /// <summary>
        /// 开始执行线程
        /// </summary>
        private void ThreadExecute(DataSourceCondition condi, string luceneSearchType)
        {
            if (!string.IsNullOrEmpty(luceneSearchType))
            {
                //  workThread = null;
                workObj.processShow = ShowProgress;
                workObj.closeForm = CloseForm;
                workObj.conditon = condi;

                workObj.LuceneSearchType = luceneSearchType.ToUpper();//设置查询lucene方法

                //workThread = new Thread(workObj.execute_Start);
                workThread = new Thread(workObj.execute_Start);
                workThread.Start();
            }
        }


        #endregion

        #region  加工条件
        /// <summary>
        /// 民事数据处理开始按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void StartBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //处理节点
                if (string.IsNullOrEmpty(txtNowProcessNode.Text.Trim()))
                {
                    MsgBox.Warn("处理节点不能为空");
                    return;
                }
                //用途
                if (string.IsNullOrEmpty(cbtPurpose.Text.Trim()))
                {
                    MsgBox.Warn("用途不能为空");
                    return;
                }
                //逻辑段
                if (string.IsNullOrEmpty(cbtParagraph.Text.Trim()))
                {
                    MsgBox.Warn("逻辑段不能为空");
                    return;
                }
                var selectTab = tabDataScope.SelectedTab;
                //数据范围为索引
                if (selectTab.TabIndex == 0)
                {
                    if (t_Case_HeadWords.Text.Trim() != "" && t_Case_JudicialProcedure.Text.Trim() != "" && t_Case_Property.Text.Trim() != "" && t_Case_ParagraphType.Text.Trim() != "" && txtNowProcessNode.Tag.ToString() != "")
                    {
                        if (workThread == null)//创建线程
                        {
                            #region 查询条件
                            //条件
                            var condi = new DataSourceCondition
                            {
                                CaseIdStart = CaseIdStart.Text.Trim(),
                                CaseIdEnd = CaseIdEnd.Text.Trim(),
                                HeadwordId = t_Case_HeadWords.Text.Split('|')[0].Trim(),// t_Case_HeadWords.Text.Trim().Substring(t_Case_HeadWords.Text.IndexOf('(') + 1).Replace(")", ""),
                                JudicialProcedureId = t_Case_JudicialProcedure.Text.Trim().ToString().Substring(t_Case_JudicialProcedure.Text.IndexOf('(') + 1).Replace(")", ""),
                                PropertyId = t_Case_Property.Text.Trim().ToString().Substring(t_Case_Property.Text.IndexOf('(') + 1).Replace(")", ""),
                                ParagraphType = t_Case_ParagraphType.Text.Trim().Substring(t_Case_ParagraphType.Text.IndexOf('(') + 1).Replace(")", ""),
                                Court = cbTreeViewSysCourt.TreeView.SelectedNode == null?"":cbTreeViewSysCourt.TreeView.SelectedNode.Tag.ToString().Trim(),// t_Global_Court.Text.Trim(),
                                SituationId = txtNowProcessNode.Tag.ToString(),
                                SearchPerSize = int.Parse(ConfigHelper.AppSettings("LuceneSearchPerSize")), //每次查询个数
                                SituationName = ccName,
                                IsHasOwnNode = chkHasOwnNode.Checked,
                                //民事新添加 todo by zhangpeng 2016-12-22
                                OperateParagraphId = !string.IsNullOrEmpty(cbtParagraph.Text) ? cbtParagraph.TreeView.SelectedNode.Tag.ToString() : null,
                                OperatePurposeId = !string.IsNullOrEmpty(cbtPurpose.Text) ? cbtPurpose.TreeView.SelectedNode.Tag.ToString() : null
                            };

                            #endregion

                            //todo by zhangpeng:Lucene查询方法（WCF或直接通过共享方法调用）两个值：WCF，Share
                            var dataProcessType = ConfigHelper.AppSettings("LuceneSearchType");

                            if (string.IsNullOrEmpty(dataProcessType)) dataProcessType = "wcf";

                            workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_first_PeopleNew");

                            //开始执行
                            ThreadExecute(condi, dataProcessType);
                        }
                        else//暂停后重启
                        {
                            MsgBox.Warn("当前操作未完成，请等待");
                          //workObj.Resume();
                        }

                    }
                    else
                    {
                        MsgBox.Warn(@"案由、案件类别、裁决程序不可为空，请重新填写!");
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.Err("系统报错，请查看错误日志!");
                workThread.Abort();
                workThread = null;
                Log.ErrorLog(ex.Message);
            }
        }

        #region  重加工
        /// <summary>
        /// 重跑数据开始(立即处理)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Start_Again(Dictionary<string, string> AddEleDic)
        {

            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");

            //NodeTree ae = NodeTree.Default;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();

            //foreach (KeyValuePair<string, string> kv in AddEleDic)//一个一个开始
            //{
            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = kv.Key;
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //Threadexecute();
        }

        /// <summary>
        /// 开始处理"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExecAllStart_Click(object sender, EventArgs e)
        {
            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");
            //conditonList.Clear();

            //DataTable AllElem = addelementbll.GetAllElement();

            //for (int i = 0; i < AllElem.Rows.Count; i++)
            //{

            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = AllElem.Rows[i]["StiuatonId"].ToString();
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //// workObj

            //Threadexecute();

            ////清库
            //wordbll.UpdateClearElement_Process();
        }


        /// <summary>
        /// 保存"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="AddEleDic"></param>
        public void SaveElement(Dictionary<string, string> AddEleDic)
        {
            //var ae = ConditionExtract.NodeTree.Instance;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //var elements = new StringBuilder();
            //foreach (var kv in AddEleDic)
            //{
            //    addelementbll.AddExpress_AddElement(kv.Key, kv.Value);
            //    elements.Append("," + kv.Value);
            //}

            //wordbll.UpdateAddElement_Process(EW_IDText, elements.ToString());
            //dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
        }


        #endregion

        #endregion

        #region 小功能（刷新关闭 有问题）


        bool closeState;
        //关闭
        private void DataProcess_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (workThread != null && workThread.IsAlive && e.CloseReason == CloseReason.UserClosing && !closeState)
            {
                workObj.Stop();

                e.Cancel = true;
            }

        }
        public void CloseForm()
        {
            if (progressBar1.InvokeRequired == false)
            {
                closeState = true;
                Close();
            }
            else
            {
                CloseForm closeForm = CloseForm;
                Invoke(closeForm);
            }
        }
        //刷新
        private void button3_Click(object sender, EventArgs e)
        {
            CaseCauseTree();
        }
        #endregion

        #region 界面显示（非核心功能）

        #region 查询节点(有问题)
        DataTable Querydt;
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                QueryNode();
            }

        }

        /// <summary>
        /// 查询
        /// </summary>
        private void QueryNode()
        {
            var queryNodeName = QueryNodeTxt.Text.Trim();

            if (queryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, queryNodeName, 2);
                StacticQuery.Text = Querydt.Rows.Count.ToString();
                if (Querydt.Rows.Count > 0)
                {
                    CurrNodeNum.Text = "1";
                    SumQuery.Text = CurrNodeNum.Text;
                    var currNode = Convert.ToInt32(CurrNodeNum.Text);
                    LinkIsVisible(currNode);
                    QueryNode_Page(Querydt, currNode);
                }
                else
                {
                    CurrNodeNum.Text = "0";
                    SumQuery.Text = CurrNodeNum.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }




        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            QueryNode();
        }
        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) + 1).ToString();
            SumQuery.Text = CurrNodeNum.Text;
            var CurrNode = Convert.ToInt32(CurrNodeNum.Text);
            QueryNode_Page(Querydt, CurrNode);
            LinkIsVisible(CurrNode);


        }
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) - 1).ToString();
            SumQuery.Text = CurrNodeNum.Text;
            var CurrNode = Convert.ToInt32(CurrNodeNum.Text);
            QueryNode_Page(Querydt, CurrNode);
            LinkIsVisible(CurrNode);

        }
        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                var NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');
                for (var i = 0; i < NotePidArr.Length; i++)
                {

                    if (i != NotePidArr.Length - 1)
                    {
                        FindNode(NotePidArr[i]).Expand();
                    }
                    else
                    {
                        var node = FindNode(NotePidArr[i]);
                        tVCaseCause.SelectedNode = node;

                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }
        /// <summary>
        /// 找到节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (var node in NodeList)
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;

        }
        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)
            {
                Prelinkbtn.Enabled = false;
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;
            }




        }
        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            var CurrNode = Convert.ToInt32(SumQuery.Text);

            if (Querydt.Rows.Count >= CurrNode)
            {
                CurrNodeNum.Text = SumQuery.Text;
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }

        }

        #endregion

        #region 各种树菜单(案由、类型)
        public void GetData(string Tname)
        {
            var dt = trbll.GetTreeHeadWords("", Tname);// 第一层
            var arrayDR = dt.Select();

            foreach (var CaseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode();

                node.Text = CaseTreeNodeRode["name"] + "(" + CaseTreeNodeRode["id"] + ")";
                node.Tag = CaseTreeNodeRode["id"];

                switch (Tname)
                {
                    //case "t_Case_HeadWords":
                    //    if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                    //    {
                    //        node.Nodes.Add(new TreeNode());
                    //    }
                    //    t_Case_HeadWords.TreeView.Nodes.Add(node);
                    //    break;
                    case "t_Case_JudicialProcedure":
                        t_Case_JudicialProcedure.TreeView.Nodes.Add(node);
                        break;
                    case "t_Case_ParagraphType":
                        t_Case_ParagraphType.TreeView.Nodes.Add(node);
                        break;

                    //case "t_Global_Court":
                    //    if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                    //    {
                    //        node.Nodes.Add(new TreeNode());
                    //    }
                    //    t_Global_Court.TreeView.Nodes.Add(node);
                    //    break;

                    case "t_Case_Property":
                        t_Case_Property.TreeView.Nodes.Add(node);
                        break;

                }



            }
        }
        public void GetTreeHeadWordsChild(TreeNode parentNode, string Tname)
        {
            var dt = trbll.GetTreeHeadWords(parentNode.Tag.ToString(), Tname);// 第一层
            var arrayDR = dt.Select();

            foreach (var CaseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode();

                node.Text = LdFormat.ObjectToString(CaseTreeNodeRode["name"]) + "(" + CaseTreeNodeRode["id"] + ")";
                node.Tag = CaseTreeNodeRode["id"];
                //判断是否有子节点
                if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);

            }

        }

        public void t_Case_HeadWords_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Case_HeadWords");
        }
        public void t_Global_Court_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Global_Court");
        }
        #endregion

        #region 刑事民事行政按钮(显示不同树)
        public void GetColor()
        {
            //button8.BackColor = Color.White;
            //button6.BackColor = Color.White;
            //button5.BackColor = Color.White;
            //button4.BackColor = Color.White;
            //button7.BackColor = Color.White;
        }
        private void button8_Click(object sender, EventArgs e)
        {
            TypeName = "刑事罪名";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        #endregion

        #region 各种排序(字长、数目)

        private void SelectAdd_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 1);
            else
                SelectText = "";

            dataPagerMain.ChangePageNumber(1);
        }

        private void SelectCut_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 0);
            else
                SelectText = "";
            dataPagerMain.ChangePageNumber(1);
        }


        private void WordLengSort_Click(object sender, EventArgs e)
        {
            sort = "WordLengSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void AlphabetSort_Click(object sender, EventArgs e)
        {
            sort = "AlphabetSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void CountSort_Click(object sender, EventArgs e)
        {
            sort = "CountSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void ISCheckSort_Click(object sender, EventArgs e)
        {
            sort = "RightSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);


        }

        private void NotCheckSort_Click(object sender, EventArgs e)
        {

        }
        private void IsMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void IsAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }



        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            AddWordBank();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            AddWordBank();
            EW_IDText = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
            textBox1.Text = "";
            textBox1.Text = dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"].Value.ToString();
            ColorWord();
        }

        private void AddWordBank()
        {
            try
            {
                var model = new SYS_WordBank_KeyWords();
                var addelement = textBox1.SelectedText;
                var wordsTextArr = addelement.Split(',', '，', ';', '；');
                foreach (var item in wordsTextArr)
                {
                    if (item != "")
                    {
                        var dt = wordbankbll.GetWB_IDByHeadword(clicknode.Tag.ToString());
                        if (dt.Rows.Count > 0)
                            model.WB_ID = dt.Rows[0]["WB_ID"].ToString();
                        else
                            model.WB_ID = clicknode.Tag.ToString();
                        model.WBK_Word = item;
                        model.WBK_Length = item.Length;
                        wordbankkeywordsbll.Add(model);
                    }
                }


                MsgBox.OK("添加词库成功！");
            }
            catch (Exception error)
            {
                MsgBox.Err("添加词库失败！");
                Log.ErrorLog(error.Message);

            }

        }

        /// <summary>
        /// 标红词库
        /// </summary>
        private void ColorWord()
        {
            #region 标红词库
            textBox1.SelectionBackColor = Color.White;

            var EW_ID = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
            //string MS_ID = dataGridView1.Rows[GridViewRowNumber].Cells["MS_ID"].Value.ToString();
            IsContentOrAddElement = 1;

            var dt = express_wordbankrelbll.Get_Express_WordBankRel(EW_ID);

            for (var i = 0; i < dt.Rows.Count; i++)
            {
                StateWord(dt.Rows[i]["WBK_Word"].ToString());

            }

            #endregion
        }

        private void StateWord(string SelectWord)
        {

            textBox1.SelectionStart = 0;
            textBox1.SelectionLength = textBox1.Text.Length;

            System.Text.RegularExpressions.MatchCollection mc;
            var r = new System.Text.RegularExpressions.Regex(SelectWord); //定义一个Regex对象实例
            mc = r.Matches(textBox1.Text);
            for (var i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                var start = mc[i].Index; //记录匹配字符的位置
                var length = (SelectWord).Length;
                textBox1.SelectionStart = start;
                textBox1.SelectionLength = length;
                textBox1.SelectionBackColor = Color.Red;
            }
        }
        #endregion

        #region 添加表述
        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddExpressWprd_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(textBox1.Text.Trim()))
                {
                    var ccId = clicknode.Tag.ToString();
                    var caseid = "1000000";
                    var ParagraphID = "150";
                    var resultText = textBox1.Text;
                    if (casecausebLL.GetSYS_CaseCauseByCCID(ccId).Rows.Count > 0)//单一节点
                    {
                        var processNodedt = work.CivilBelongCaseCauseId(ccId);//节点匹配数据开始处
                        if (processNodedt.Rows.Count > 0)
                        {
                            work.AddToExpress(resultText, caseid, ParagraphID, processNodedt.Rows[0]["CC_ID"].ToString(), ccId);
                        }
                        else
                        {
                            MsgBox.Warn("添加失败,未找到符合条件的根节点");
                            return;
                        }
                    }
                    else//组合节点
                    {
                        #region 添加文本
                        var WordModel = new SYS_Express_Word();
                        WordModel.MS_ID = ccId;
                        WordModel.EW_CaseId = caseid;
                        WordModel.EW_Content = resultText;
                        WordModel.EW_UseCount = 1;
                        WordModel.EW_WordCount = resultText.Length;
                        WordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);
                        WordModel.EW_ID = wordbll.Exists_WordProcess(WordModel);
                        if (WordModel.EW_ID == "")
                        {
                            WordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                            WordModel.EW_Right = 0;
                            WordModel.EW_Wrong = 0;
                            wordbll.AddWord_Process(WordModel);
                        }
                        else
                        {
                            wordbll.UpdateWord_Process(WordModel);
                        }
                        #endregion

                        #region 词库
                        var EW_AddElementStr = express_wordbankrelbll.WordBank("", WordModel.EW_Content);
                        foreach (var item in EW_AddElementStr)
                        {
                            if (!express_wordbankrelbll.Exists(WordModel.EW_ID, item))
                            {
                                express_wordbankrelbll.Add_Express_WordBankRel(newid.JudgeDoc_CreateID("SYS_Express_WordBankRel"), WordModel.EW_ID, item);
                            }
                        }
                        #endregion
                    }
                    dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
                    textBox1.Text = "";
                    MessageBox.Show("添加表述成功！");
                }
                else
                {
                    MessageBox.Show("请填入需要添加的表述！");
                    textBox1.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加表述失败！");
                Log.ErrorLog(ex.ToString());
            }
        }
        #endregion



        private void button10_Click(object sender, EventArgs e)
        {
            OpenNodeTree();
        }

        private void OpenNodeTree()
        {
            if (clicknode != null)
            {
                //var nt1 = ConditionExtract.NodeTree.Instance;
                //nt1.Close();
                var nt =new ConditionExtract.NodeTree();
                ConditionExtract.NodeTree.TypeName = TypeName;
                nt.FirId = FirId;
                nt.LocateNode = expresitu.GetES_SituationIdsById(clicknode.Tag.ToString());
                if (nt.LocateNode.Contains(","))
                {
                    nt.LocateNode = nt.LocateNode.Substring(0, nt.LocateNode.IndexOf(","));
                }

                nt.StartPosition = FormStartPosition.CenterParent;
                nt.Show();
                nt.Activate();//激活焦点
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private TreeNode editnode;//点击获得当前节点
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            var ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
            }
        }
        private void 添加要素ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private void AddNodeMenuItem_Click(object sender, EventArgs e)
        {
            group_add.Visible = true;
            //if (clicknode != null)
            //{
            //    //ConditionExtract.NodeTree nt1 = ConditionExtract.NodeTree.Instance;
            //    //nt1.Close();
            //    ConditionExtract.NodeTree nt =new ConditionExtract.NodeTree();
            //    ConditionExtract.NodeTree.TypeName = TypeName;
            //    nt.FirId = FirId;
            //    nt.LocateNode = clicknode.Tag.ToString();
            //    //nt.LocateNode = expresitu.GetES_SituationIdsById(clicknode.Tag.ToString());
            //    //  if (nt.LocateNode.Contains(","))
            //    //  {
            //    //      nt.LocateNode = nt.LocateNode.Substring(0, nt.LocateNode.IndexOf(","));
            //    //  }
            //    ((MainForm)this.Parent.Parent).ShowForm(nt);
            //}
        }


        private void btn_quit_Click(object sender, EventArgs e)
        {
            group_add.Visible = false;
            TxtCC_ID.Text = "";
            IsMatch2.Checked = true;
            IsAffirmIdeaResult2.Checked = true;
            MatchSource.Text = "0";
            AffirmIdeaSource.Text = "0";

        }

        /// <summary>
        /// 添加节点（只能在组合下添加）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)
        {
            var newModel = new SYS_Express_MatchSituation();
            var ccId = TxtCC_ID.Text;
            newModel.IsMatch = IsMatch2.Checked ? 1 : 0;
            newModel.MatchSource = MatchSource.Text;
            newModel.AffirmIdeaResult = IsAffirmIdeaResult2.Checked ? "1" : "2";
            newModel.AffirmIdeaSource = AffirmIdeaSource.Text;

            var MS_ID = dataprocess_editnode.AddNode(ccId, editnode.Tag.ToString(), newModel);
            //添加完以后界面显示
            if (MS_ID != "")
            {
                MessageBox.Show("添加成功！");
                newModel = express_matchsituationbll.GetMatchSituation(MS_ID);
                clicknode.Expand();
                var addnode = new TreeNode();
                addnode.Tag = newModel.MS_ID;
                addnode.Text = newModel.SituationName;
                addnode.Name = newModel.SituationType.ToString();
                clicknode.Nodes.Add(addnode);
            }
            else
            {
                MessageBox.Show("添加失败，节点只能在组合部分添加！");
            }
            group_add.Visible = false;
        }


        #region 情形情节树(条件)
        /// <summary>
        /// 选择树以后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AfterCheckClick(object sender, TreeViewEventArgs e)
        {
            //NowProcessNode.TreeView.AfterCheck -= AfterCheckClick;
            //NowProcessNode.TreeView.

            //获取选择节点ID
            //var nodeId = e.Node.Tag.ToString();
            //var key = e.Node.Name;

            if (e.Node.Nodes.Count > 0)
            {
                foreach (TreeNode childNode in e.Node.Nodes)
                {
                    //判断当前节点是否选中
                    ChangeNodeCheckState(childNode, e.Node.Checked);
                }
            }

            //if (!e.Node.Checked)
            //{
            //    if (e.Node.Parent != null && e.Node.Parent is TreeNode)
            //    {
            //        e.Node.Parent.Checked = false;
            //    }
            //}

            //if (e.Node.Parent != null && e.Node.Parent is TreeNode)
            //{
            //    bool parentNode = true;
            //    foreach (TreeNode tn in e.Node.Parent.Nodes)
            //    {
            //        if (tn.Checked == false)
            //        {
            //            parentNode = false;
            //            break;
            //        }
            //    }
            //    if (e.Node.Parent.Checked != parentNode && (e.Node.Checked == false || (e.Node.Checked && e.Node.Parent.Checked == false)))
            //    {
            //        e.Node.Parent.Checked = parentNode;
            //    }
            //}

            //NowProcessNode.TreeView.AfterCheck += AfterCheckClick;




        }

        private void ChangeNodeCheckState(TreeNode sourceNode, bool isCheck)
        {
            sourceNode.Checked = isCheck;

        }

        /// <summary>
        /// 获取所有选择的节点
        /// </summary>
        /// <param name="node">树</param>
        /// <param name="selectStr">选择后的节点</param>
        private void GetCheckNodes(TreeNode node, ref IList<string> selectStr)
        {
            if (node != null)
            {
                if (node.Checked)
                    selectStr.Add(node.Tag.ToString());
                //判断子节点是否为空
                if (node.Nodes.Count > 0)
                {
                    foreach (TreeNode item in node.Nodes)
                    {
                        GetCheckNodes(item, ref selectStr);
                    }
                }

            }
        }


        /// <summary>
        /// 树（第一级）
        /// </summary>
        public void CaseCauseTree_Process()
        {
            //NowProcessNode.

            //关于NowProcessNode复选功能，暂时停止。先开发其他紧要功能 todo by zhangpeng 2016-12-21
            //设置处理节点树的展现形式
            //NowProcessNode.TreeView.CheckBoxes = true;
            //加入check选择的事件
            //NowProcessNode.TreeView.AfterCheck += (sender, args) => { AfterCheckClick(sender, args); };

            ////添加弹出框关闭事件
            //NowProcessNode.DropDownList.Closing += (sender, args) =>
            //{
            //    //获取所有选择的节点
            //    GetCheckNodes(NowProcessNode.TreeView.TopNode, ref _selectCcIdList);

            //    NowProcessNode.Text = _selectCcIdList != null && _selectCcIdList.Any()
            //        ? _selectCcIdList.Distinct().ListToString(",")
            //        : null;
            //};

            //var dt = trbll.NodeTree_Tree("");
            //var arrayDR = dt.Select("name='" + "民事案由" + "'");

            //foreach (var caseTreeNodeRode in arrayDR)
            //{
            //    var node = new TreeNode
            //    {
            //        Text =
            //            LdFormat.ObjectToString(caseTreeNodeRode[1]) + "(" +
            //            LdFormat.ObjectToString(caseTreeNodeRode[0]) + ")",
            //        Tag = caseTreeNodeRode[0],
            //        Name = LdFormat.ObjectToString(caseTreeNodeRode[2])
            //    };

            //    FirId = caseTreeNodeRode[0].ToString();
            //    if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
            //    {
            //        node.Nodes.Add(new TreeNode());
            //    }
            //    //txtNowProcessNode.TreeView.Nodes.Add(node);
            //}


            //DataTable dt = trbll.AllGetCaseCause("民事案由");

            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    //转换成list对象
            //    var list = dt.AsEnumerable().ToList();
            //    foreach (DataRow caseTreeNodeRode in list)
            //    {
            //        var node = new TreeNode
            //        {
            //            Text =
            //                LdFormat.ObjectToString(caseTreeNodeRode[1]) + "(" +
            //                LdFormat.ObjectToString(caseTreeNodeRode[0]) + ")",
            //            Tag = caseTreeNodeRode[0],
            //            Name = LdFormat.ObjectToString(caseTreeNodeRode[3])
            //        };

            //        FirId = caseTreeNodeRode[0].ToString();
            //        if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
            //        {
            //            node.Nodes.Add(new TreeNode());
            //        }

            //        GenernateNode(node, list);

            //        NowProcessNode.TreeView.Nodes.Add(node);
            //    }
            //}


        }

        /// <summary>
        /// 生成节点列表
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="sourceList">数据源</param>
        private void GenernateNode(TreeNode parentNode, IList<DataRow> sourceList)
        {
            //DataTable dt = trbll.NodeTree_Tree(parentNode.Tag.ToString());
            //DataRow[] arrayDR = dt.Select("name='" + "民事案由" + "'");



            if (sourceList != null && sourceList.Any(x => x[0].ToString() == parentNode.Tag.ToString()))
            {
                foreach (var caseTreeNodeRode in sourceList.Where(x => x[3].ToString() == parentNode.Tag.ToString()))
                {
                    var node = new TreeNode
                    {
                        Text =
                            LdFormat.ObjectToString(caseTreeNodeRode[1]) + "(" +
                            LdFormat.ObjectToString(caseTreeNodeRode[0]) + ")",
                        Tag = caseTreeNodeRode[0],
                        Name = LdFormat.ObjectToString(caseTreeNodeRode[3])
                    };

                    FirId = caseTreeNodeRode[0].ToString();

                    GenernateNode(node, sourceList);

                    parentNode.Nodes.Add(node);
                }

            }

        }


        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild_Process(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();
            var caseTreeNodeRode = trbll.NodeTree_Tree(pid);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode
                {
                    Text = caseTreeNodeRode.Rows[i]["name"] + @"(" + caseTreeNodeRode.Rows[i]["id"] + @")",
                    Tag = caseTreeNodeRode.Rows[i]["id"],
                    Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"])
                };


                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                node.Checked = parentNode.Checked;
                parentNode.Nodes.Add(node);
            }
        }

        private void NowProcessNode_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild_Process(e.Node);
        }


        /// <summary>
        /// 处理节点变化事件，重新加载用途
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NowProcessNode_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNowProcessNode.Text))
                return;

            //清空用途combobox和逻辑段combobox
            cbtPurpose.TreeView.Nodes.Clear();
            cbtParagraph.TreeView.Nodes.Clear();
            cbtParagraph.Text = cbtPurpose.Text = "";

            //根据所选节点，获取该节点对应的表述用途列表
            GetPurposeList(txtNowProcessNode.Tag.ToString());

        }

        /// <summary>
        /// 根据所选节点，获取该节点对应的表述用途列表
        /// </summary>
        /// <param name="ccId">节点ID</param>
        /// <param name="isHasChild">是否包括该节点以下的所有子节点的用途</param>
        private void GetPurposeList(string ccId, bool isHasChild = false)
        {
            //todo by zhangpeng:是否包括该节点以下的所有子节点的用途,该功能暂时不实现，因为似乎是不符合逻辑的

            //根据CCID，获取对应节点的用途列表（去重）
            var dt = sourceBll.GetPurposeDtByCcid(ccId);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dataRow in dt.Rows)
                {
                    var node = new TreeNode
                    {
                        Text = dataRow["AM_Name"].ToString(),
                        Tag = dataRow["AM_ID"]
                    };
                    cbtPurpose.TreeView.Nodes.Add(node);
                }

            }

        }

        /// <summary>
        /// 用途文本变化，添加对应的逻辑段列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbtPurpose_TextChanged(object sender, EventArgs e)
        {
            //清空逻辑段
            cbtParagraph.TreeView.Nodes.Clear();


            if (string.IsNullOrEmpty(txtNowProcessNode.Tag.ToString()) || string.IsNullOrEmpty(cbtPurpose.Text))
                return;

            //根据CCID和用途ID，查询对应的逻辑段
            var dt = sourceBll.GetParagraphDtByCcidAndPurpose(txtNowProcessNode.Tag.ToString(), cbtPurpose.TreeView.SelectedNode.Tag.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dataRow in dt.Rows)
                {
                    var node = new TreeNode
                    {
                        Text = dataRow["Source_ParagraphName"] + "(" + dataRow["Source_Name"] + ")",
                        Tag = dataRow["Source_ParagraphID"]
                    };
                    cbtParagraph.TreeView.Nodes.Add(node);
                }
            }
        }


        #endregion

        private void GV_Reg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex >= 0)
            {
                if (GV_Reg.Rows[e.RowIndex].Cells[3].Value != null)
                {
                    var EI_ID = GV_Reg.Rows[e.RowIndex].Cells[3].Value.ToString();
                    if (EI_ID != "")
                    {
                        Random rd = new Random();
                        ShowRegexData sr = new ShowRegexData(ConfigHelper.AppSettings("RegexSystemUrl") + "/RegexEdit.aspx?EIID=" + EI_ID + "&a=" + rd.Next(10000, 20000));
                        sr.ShowDialog();
                    }
                }
            }

        }


        private void AgainOrganTree_Click(object sender, EventArgs e)
        {
            if (workThread == null)//创建线程
            {
                #region 查询条件

                var condi = new DataSourceCondition(); //条件
                #endregion

                workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_Order");
                ThreadExecute(condi, null);

            }

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }

        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {

            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();

            //DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            //if (caseTreeNodeRode.Rows.Count == 0)
            //    return;
            //for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            //{
            //    TreeNode node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
            //    node.Tag = caseTreeNodeRode.Rows[i]["id"];
            //    node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
            //    AllExpandNode(node.Tag.ToString());
            //}
        }



        /// <summary>
        /// 查看案例逻辑段，根据案例caseId和逻辑段ID
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchSourceCase_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedCells.Count > 0)
            {
                var rowIndex = dataGridView1.SelectedCells[0].RowIndex;
                if (rowIndex != -1)
                {
                    var caseId = int.Parse(dataGridView1.Rows[rowIndex].Cells["EW_CaseId"].Value.ToString());
                    //获取指定案例ID和逻辑段120的逻辑段内容
                    var dt = wordbll.GetCaseParagraphLogic(caseId, 120);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        var childForm = FrmExpressDetail.Default;
                        childForm.ExpressText = dt.Rows[0]["ParagraphText"].ToString();
                        childForm.StartPosition = FormStartPosition.CenterParent;
                        childForm.Show();
                        childForm.Activate();

                    }
                }
            }



        }

        #region 查询节点
        /// <summary>
        /// 查询节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProcessNodeSearch_Click(object sender, EventArgs e)
        {
            var frm = new FrmNodeSelect { TypeName = "民事案由" };
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                var strResult = frm.Tag.ToString();
                frm.Close();
                if (!string.IsNullOrEmpty(strResult))
                {
                    var strArray = strResult.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    txtNowProcessNode.Tag = strArray[0];
                    ccName = strArray[1].ToString();
                    txtNowProcessNode.Text = strArray[0] + @"(" + strArray[1] + @")";
                }

            }




        }














        #endregion

        private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowData sd = new ShowData(this.textBox1.Text);
            sd.ShowDialog();
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            //textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
            textBox1.Text = this.dataGridView1.CurrentRow.Cells["EW_Content"].Value.ToString();
            NewMethod();
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                if (Convert.ToBoolean(check.Value))
                {
                    //StringBuilder sb = new StringBuilder();
                    //DataTable dt = (DataTable)GV_Reg.DataSource;
                    //if (dt != null && dt.Rows.Count > 0)
                    //{
                    //    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[\u4e00-\u9fa5]+");//正则表达式
                    //    foreach (DataRow item in dt.Rows)
                    //    {
                    //        foreach (Match v in reg.Matches(item["ER_RegexText"].ToString()))
                    //        {
                    //            sb.Append(v.ToString() + ",");
                    //        }
                    //    }
                    //}
                    //string item1 = sb.ToString();
                    ShowParagraphData sd = new ShowParagraphData(this.dataGridView1.Rows[i].Cells["EW_CaseId"].Value.ToString());
                    sd.ShowDialog();
                }
            }

        }


        /// <summary>
        /// 案由文本框文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void t_Case_HeadWords_TextUpdate(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(t_Case_HeadWords.Text))
            {

                if (sysCaseCauseTable.Select("ID like '%" + t_Case_HeadWords.Text + "%' or Name like '%" + t_Case_HeadWords.Text + "%'").Length > 0)
                {
                    DataTable dt3 = sysCaseCauseTable.Select(" ID like '%" + t_Case_HeadWords.Text + "%' or Name like '%" + t_Case_HeadWords.Text + "%'").CopyToDataTable<DataRow>();
                    t_Case_HeadWords.TreeView.Nodes.Clear();
                    if (dt3 != null && dt3.Rows.Count > 0)
                    {
                        if (dt3.Rows.Count == 1)
                        {
                            t_Case_HeadWords.Text = dt3.Rows[0]["ID"].ToString() + "|" + dt3.Rows[0]["Name"].ToString();
                        }
                        else
                        {
                            for (int i = 0; i < dt3.Rows.Count; i++)
                            {
                                TreeNode node = new TreeNode();
                                node.Text = dt3.Rows[i]["Name"].ToString();
                                node.Tag = dt3.Rows[i]["ID"].ToString();
                                if (sysCourtTable.Select("ParentID='" + node.Tag + "'").Length > 0)
                                {
                                    node.Nodes.Add(new TreeNode());
                                }
                                t_Case_HeadWords.TreeView.Nodes.Add(node);
                            }
                        }
                    }
                }
                else
                {
                    t_Case_HeadWords.TreeView.Nodes.Clear();
                }
            }
            else
            {
                t_Case_HeadWords.TreeView.Nodes.Clear();
                LoadSysCaseCauseData();
            }
        }
    }
}